#include "stdafx.h"
#include "vol_user_app_info.h"

CMailslot::CMailslot()
{
    hMailsolt = INVALID_HANDLE_VALUE;
    hFile = INVALID_HANDLE_VALUE;
    m_dwMaxMessageSize = 0;
}

CMailslot::~CMailslot()
{
    Close();
}

BOOL CMailslot::Create(LPCTSTR lpMailsoltName, DWORD dwMaxMessageSize)
{
    Close();

    if (IsEmptyStr(lpMailsoltName) || dwMaxMessageSize == 0)
        return FALSE;
    TCHAR lpName[MAX_PATH] = _T("\\\\.\\mailslot\\");
    _tcscat_s(lpName, lpMailsoltName);
    m_dwMaxMessageSize = dwMaxMessageSize;
    hMailsolt = CreateMailslot(lpName, m_dwMaxMessageSize, MAILSLOT_WAIT_FOREVER, NULL);
    return (hMailsolt != INVALID_HANDLE_VALUE);
}

BOOL CMailslot::Open(LPCTSTR lpServerName, LPCTSTR lpMailsoltName)
{
    Close();
    
    if (IsEmptyStr(lpServerName) || IsEmptyStr(lpMailsoltName))
        return FALSE;
    TCHAR lpName[MAX_PATH] = _T("\\\\");
    _tcscat_s(lpName, lpServerName);
    _tcscat_s(lpName, _T("\\mailslot\\"));
    _tcscat_s(lpName, lpMailsoltName);

    hFile = CreateFile(lpName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    return (hFile != INVALID_HANDLE_VALUE);
}

BOOL CMailslot::Read(LPVOID lpBuffer, LPDWORD lpBufSize, LPDWORD lpReadSize)
{
    if (NULL == hMailsolt)
        return FALSE;

    DWORD dwNextSize = 0;
    if (GetMailslotInfo(hMailsolt, NULL, &dwNextSize, NULL, NULL) == FALSE) 
        return FALSE;
    if ( MAILSLOT_NO_MESSAGE == dwNextSize) 
        return FALSE;
    return ReadFile(hMailsolt, lpBuffer, *lpBufSize, lpReadSize, NULL);
}


BOOL CMailslot::Write(PVOID pvData, DWORD dwSize)
{
    if (NULL == hFile)
        return 0;
    return WriteFile(hFile, pvData, dwSize, NULL, (LPOVERLAPPED)NULL);
}

VOID CMailslot::Close()
{
    if (INVALID_HANDLE_VALUE != hFile)
    {
        CloseHandle(hFile);
        hFile = INVALID_HANDLE_VALUE;
    }
    if (INVALID_HANDLE_VALUE != hMailsolt)
    {
        CloseHandle(hMailsolt);
        hMailsolt = INVALID_HANDLE_VALUE;
    }
    m_dwMaxMessageSize = 0;
}